class Solution:
    """
    自底向上
    """
    def minPathSum(self, grid) -> int:
        if not grid and not grid[0]:
            return 0

        rows, columns = len(grid), len(grid[0])

        dp = [[0] * columns for _ in range(rows)]
        dp[0][0] = grid[0][0]
        for column in range(1, columns):
            dp[0][column] = dp[0][column-1] + grid[0][column]

        for row in range(1, rows):
            dp[row][0] = dp[row-1][0] + grid[row][0]

        for i in range(1, rows):
            for j in range(1, columns):
                dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]

        
        return dp[-1][-1]



if __name__ == '__main__':
    s = Solution()
    grid = [[1,3,1],[1,5,1],[4,2,1]]
    print(s.minPathSum(grid))
    